﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace LP580.CG
{
    /// <summary>
    /// clsAdmin 的摘要说明
    /// <summary>
    public class clsAdmin
    {
        private static readonly string _CkValidKey = "admv";

        #region 构造函数

        public clsAdmin() { }

        public clsAdmin(int prmAdminID)
        {
            clsAdmin entity = clsAdmin.GetByKey(prmAdminID);
            this._adminid = entity._adminid;
            this._adminname = entity._adminname;
            this._adminpassword = entity._adminpassword;
            this._islocked = entity._islocked;
            this._adminallowip = entity._adminallowip;
            this._adminroleid = entity._adminroleid;
        }

        #endregion

        public static clsAdmin GetByKey(int prmAdminID)
        {
            clsAdmin entity = new clsAdmin();
            DBase dbo = new DBase();
            System.Data.IDataReader dr = dbo.ExecuteReader("SELECT * FROM [tbl_Admin] WHERE [AdminID]=" + prmAdminID.ToString());
            if (dr.Read())
            {
                entity = DrToClass(dr);
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return entity;
        }

        private static clsAdmin DrToClass(System.Data.IDataReader dr)
        {
            clsAdmin entity = new clsAdmin();

            int iTmp = 0;
            if (!int.TryParse(dr["AdminID"].ToString(), out iTmp))
                iTmp = 0;
            entity._adminid = iTmp;
            entity._adminname = dr["AdminName"].ToString();
            entity._adminpassword = dr["AdminPassword"].ToString();
            bool bTmp = false;
            if (!bool.TryParse(dr["isLocked"].ToString(), out bTmp))
                bTmp = false;
            entity._islocked = bTmp;
            entity._adminallowip = dr["AdminAllowIP"].ToString();
            iTmp = 0;
            if (!int.TryParse(dr["AdminRoleID"].ToString(), out iTmp))
                iTmp = 0;
            entity._adminroleid = iTmp;

            return entity;
        }

        /// <summary>
        /// 权限模块
        /// </summary>
        /// <param name="PurviewStr"></param>
        /// <param name="Moulde"></param>
        /// <returns></returns>
        public bool chkPurview(string PurviewStr, string Moulde)
        {
            bool rv = false;
            string[] arr = PurviewStr.Split(',');
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == Moulde || PurviewStr == "ALL")
                {
                    rv = true;
                    break;
                }
            }
            return rv;
        }

        /// <summary>
        /// 验证管理员
        /// </summary>
        /// <returns></returns>
        public static bool ValidAdmin(string adminname, string adminpassword)
        {
            return (ValidAdminReturnID(adminname, adminpassword) > 0);
        }

        /// <summary>
        /// 验证管理员
        /// </summary>
        /// <returns>成功返回ID值，否则为0</returns>
        public static int ValidAdminReturnID(string adminname, string adminpassword)
        {
            int iID = 0;
            if (adminname != "" && adminpassword != "")
            {
                string sql = string.Format("SELECT AdminID FROM [tbl_Admin] WHERE [isLocked]=0 AND [AdminName]='{0}' AND [AdminPassword] = '{1}'", adminname, adminpassword);
                DBase dbo = new DBase();
                System.Data.IDataReader dr = dbo.ExecuteReader(sql);
                if (dr.Read())
                {
                    iID = Convert.ToInt32(dr[0]);
                }
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
            }
            return iID;
        }


        /// <summary>
        /// 处理登陆
        /// </summary>
        public static void doLogin(clsAdmin adm)
        {
            clsAdmin.setLoginCookie(adm);
        }

        /// <summary>
        /// 处理登出
        /// </summary>
        public static void doLogout()
        {
            if (HttpContext.Current.Request.Cookies[clsAdmin._CkValidKey] != null)
            {
                HttpCookie myCookie = new HttpCookie(clsAdmin._CkValidKey);
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                HttpContext.Current.Response.Cookies.Add(myCookie);
            }
        }

        /// <summary>
        /// 保存管理员凭证Cookie信息
        /// </summary>
        /// <param name="adm"></param>
        public static void setLoginCookie(clsAdmin adm)
        {
            HttpCookie myCookie = new HttpCookie(clsAdmin._CkValidKey);
            myCookie["u"] = Utils.Encrypt(adm._adminname);
            myCookie["p"] = Utils.Encrypt(adm._adminpassword);
            //myCookie.Expires = DateTime.Now.AddDays(30d);
            HttpContext.Current.Response.Cookies.Add(myCookie);
        }

        /// <summary>
        /// 取Cookie保存凭证管理员
        /// </summary>
        /// <returns></returns>
        public static clsAdmin getCookieAdmin()
        {
            string no = "", pass = "";
            if (HttpContext.Current.Request.Cookies[clsAdmin._CkValidKey] != null)
            {
                if (HttpContext.Current.Request.Cookies[clsAdmin._CkValidKey]["u"] != null)
                {
                    no = Utils.Decrypt(HttpContext.Current.Request.Cookies[clsAdmin._CkValidKey]["u"]);
                }
                if (HttpContext.Current.Request.Cookies[clsAdmin._CkValidKey]["p"] != null)
                {
                    pass = Utils.Decrypt(HttpContext.Current.Request.Cookies[clsAdmin._CkValidKey]["p"]);
                }
            }

            clsAdmin adm = null;

            /*****便于开发调试，完成开发后请注释掉此部份内容*******/             
            adm = new clsAdmin();
            adm._adminid = 0;
            adm._adminname = "TEST ADMIN";
            return adm;
            /****************************************************/

            if (no != "" && pass != "")
            {
                int iTmpAdminID = clsAdmin.ValidAdminReturnID(no, pass);
                if (iTmpAdminID > 0)
                    adm = new clsAdmin(iTmpAdminID);
            }
            return adm;
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <returns></returns>
        public static bool ExistAdminName(string name)
        {
            bool rv = true;
            if (name != "")
            {
                string sql = string.Format("SELECT AdminID FROM [tbl_Admin] WHERE [AdminName]='{0}'", name);
                DBase dbo = new DBase();
                System.Data.IDataReader dr = dbo.ExecuteReader(sql);
                rv = dr.Read();
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
            }
            return rv;
        }

        public void ChangPass()
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql = "UPDATE [tbl_Admin] SET [AdminPassword] = @AdminPassword WHERE [AdminName]=@AdminName";
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@AdminPassword", this._adminpassword);
            SaveDTM.AddNewParam("@AdminName", this._adminname);
            SaveDTM.Update();
        }

        #region 增删改数据库操作

        public static int Insert(clsAdmin prmEntity)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = string.Format("insert into [tbl_Admin](" +
                            " [AdminName]," +
                            " [AdminPassword]," +
                            " [isLocked]," +
                            " [AdminAllowIP]," +
                            " [AdminRoleID]" +
            ") values (" +
                    "@AdminName," +
                    "@AdminPassword," +
                    "@isLocked," +
                    "@AdminAllowIP," +
                    "@AdminRoleID" +
            ")");
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@AdminName", prmEntity._adminname);
            SaveDTM.AddNewParam("@AdminPassword", prmEntity._adminpassword);
            SaveDTM.AddNewParam("@isLocked", prmEntity._islocked);
            SaveDTM.AddNewParam("@AdminAllowIP", prmEntity._adminallowip);
            SaveDTM.AddNewParam("@AdminRoleID", prmEntity._adminroleid);
            SaveDTM.Insert();
            return 1;
        }

        public static bool Delete(int prmAdminID)
        {
            DBase dbo = new DBase();
            dbo.ExecSql("DELETE FROM [tbl_Admin] WHERE AdminID=" + prmAdminID.ToString());
            dbo.CloseConn();
            dbo = null;
            return true;
        }

        public static bool Update(clsAdmin prmEntity)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = "UPDATE [tbl_Admin] SET " +
                "[AdminName] = @AdminName, " +
                "[AdminPassword] = @AdminPassword, " +
                "[isLocked] = @isLocked, " +
                "[AdminAllowIP] = @AdminAllowIP, " +
                "[AdminRoleID] = @AdminRoleID " +
            " WHERE AdminID=@AdminID";
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@AdminName", prmEntity._adminname);
            SaveDTM.AddNewParam("@AdminPassword", prmEntity._adminpassword);
            SaveDTM.AddNewParam("@isLocked", prmEntity._islocked);
            SaveDTM.AddNewParam("@AdminAllowIP", prmEntity._adminallowip);
            SaveDTM.AddNewParam("@AdminRoleID", prmEntity._adminroleid);
            SaveDTM.AddNewParam("@AdminID", prmEntity._adminid);
            SaveDTM.Update();
            return true;
        }

        #endregion

        public static List<clsAdmin> GetCollection()
        {
            List<clsAdmin> ls = new List<clsAdmin>();
            DBase dbo = new DBase();
            string sql = "SELECT * FROM [tbl_Admin] ORDER BY AdminID DESC";
            System.Data.IDataReader dr = dbo.ExecuteReader(sql);
            while (dr.Read())
            {
                ls.Add(DrToClass(dr));
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return ls;
        }

        #region 字段属性

        private int _adminid = 0;
        /// <summary>
        /// 管理员ID-自增
        /// </summary>
        public int AdminID
        {
            get { return _adminid; }
            set { _adminid = value; }
        }

        private string _adminname = "";
        /// <summary>
        /// 管理员帐号名
        /// </summary>
        public string AdminName
        {
            get { return _adminname; }
            set { _adminname = value; }
        }

        private string _adminpassword = "";
        /// <summary>
        /// 管理员密码
        /// </summary>
        public string AdminPassword
        {
            get { return _adminpassword; }
            set { _adminpassword = value; }
        }

        private bool _islocked = false;
        /// <summary>
        /// 是否被锁无法登入
        /// </summary>
        public bool isLocked
        {
            get { return _islocked; }
            set { _islocked = value; }
        }

        private string _adminallowip = "";
        /// <summary>
        /// 被允许管理登入的IP
        /// </summary>
        public string AdminAllowIP
        {
            get { return _adminallowip; }
            set { _adminallowip = value; }
        }

        private int _adminroleid = 0;
        /// <summary>
        /// 管理员权限角色ID
        /// </summary>
        public int AdminRoleID
        {
            get { return _adminroleid; }
            set { _adminroleid = value; }
        }

        #endregion
    }
}

